package com.example.projectmanagement.controller;

import com.example.projectmanagement.aop.LogOperation;
import com.example.projectmanagement.dto.LoginRequest;
import com.example.projectmanagement.dto.LoginResponse;
import com.example.projectmanagement.dto.UserDto;
import com.example.projectmanagement.model.User;
import com.example.projectmanagement.model.Role;
import com.example.projectmanagement.repository.UserRepository;
import com.example.projectmanagement.security.JwtUtil;
import com.example.projectmanagement.service.UserService;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import java.time.LocalDateTime;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtUtil jwtUtil;

    @PostMapping("/login")
    @LogOperation(operationType = "LOGIN", module = "认证系统", description = "用户登录")
    public ResponseEntity<?> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            // 获取用户信息
            User user = userRepository.findByUsername(loginRequest.getUsername())
                    .orElseThrow(() -> new RuntimeException("User not found"));

            // 检查账号是否被锁定
            if (user.getLoginFailCount() >= 3 && user.getLockTime() != null &&
                    user.getLockTime().isAfter(LocalDateTime.now())) {
                return ResponseEntity.badRequest()
                        .body("Account is locked. Please try again later.");
            }

            // 认证用户
            Authentication authentication = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(
                            loginRequest.getUsername(),
                            loginRequest.getPassword()
                    )
            );

            SecurityContextHolder.getContext().setAuthentication(authentication);

            // 重置登录失败次数
            user.setLoginFailCount(0);
            user.setLockTime(null);
            userRepository.save(user);

            // 生成JWT token
            String token = jwtUtil.generateToken(user.getUsername());

            // 获取用户角色
            List<String> userRoles = userService.getUserRoles(user.getId()).stream()
                    .map(role -> role.getRoleName())
                    .collect(Collectors.toList());

            // 创建用户信息对象
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo(
                    user.getId(),
                    user.getUsername(),
                    user.getName(),
                    user.getDepartment() != null ? user.getDepartment() : "",
                    userRoles,
                    user.getAvatar() != null ? user.getAvatar() : ""
            );

            // 创建登录响应
            LoginResponse response = new LoginResponse(token, userInfo);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            // 更新登录失败次数
            User user = userRepository.findByUsername(loginRequest.getUsername()).orElse(null);
            if (user != null) {
                int failCount = user.getLoginFailCount() + 1;
                user.setLoginFailCount(failCount);

                // 如果失败次数达到3次，锁定账号30分钟
                if (failCount >= 3) {
                    user.setLockTime(LocalDateTime.now().plusMinutes(30));
                }

                userRepository.save(user);
            }

            return ResponseEntity.badRequest().body("Invalid username or password");
        }
    }

    @PostMapping("/register")
    @LogOperation(operationType = "CREATE", module = "认证系统", description = "用户注册")
    public ResponseEntity<?> register(@Valid @RequestBody UserDto userDto) {
        try {
            // 检查用户名是否已存在
            if (userRepository.existsByUsername(userDto.getUsername())) {
                return ResponseEntity.badRequest().body("Username already exists");
            }

            // 创建新用户
            User user = userService.createUser(userDto);

            // 获取用户角色
            List<String> userRoles = userService.getUserRoles(user.getId()).stream()
                    .map(role -> role.getRoleName())
                    .collect(Collectors.toList());

            // 创建用户信息对象
            LoginResponse.UserInfo userInfo = new LoginResponse.UserInfo(
                    user.getId(),
                    user.getUsername(),
                    user.getName(),
                    user.getDepartment() != null ? user.getDepartment() : "",
                    userRoles,
                    user.getAvatar() != null ? user.getAvatar() : ""
            );

            // 生成JWT token
            String token = jwtUtil.generateToken(user.getUsername());

            // 创建登录响应
            LoginResponse response = new LoginResponse(token, userInfo);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Registration failed: " + e.getMessage());
        }
    }
}